import React from 'react';
import {inject, observer} from 'mobx-react';
import {autorun, toJS} from 'mobx';
import {Spin, Alert, Button, Modal, message} from 'antd';
import {WeaTools, WeaTab, WeaPopoverHrm, WeaBrowser, WeaNewScrollPagination, WeaInput, WeaLocaleProvider} from 'ecCom';
import './style/';

const getLabel = WeaLocaleProvider.getLabel;

@inject("ReportElementViewStore", "ReportElementSettingStore", "StringUtilsStore")
@observer
class View extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            topTab: [],
            counts: {},
            currListDatas: [],
            currListPageNum: "1",
            pageSize: "6",
            currListFirstQueryTotal: "",         // 当前tab页列表的首次查询数据总数，并不是该tab页的所有数据的总数
            loading: false,
            selectedTabKey: "1",
            right: ""
        }
    }

    componentWillMount() {
        WeaTools.callApi('/api/workrelate/common/checkHasRigth', 'GET', {id: "4"}).then((result) => {
            if (result.isRight) {
                this.setState({
                    right: "1"
                }, () => {
                    this.doNext()
                })
            } else {
                this.setState({
                    right: "0"
                })
            }
        })
    }

    componentDidMount () {

    }

    doNext = () => {
        const {params = {}, ReportElementViewStore, ReportElementSettingStore} = this.props;
        const {eid} = params;

        WeaTools.callApi('/api/workrelate/portal/element/getSettingData', 'GET', {eid}).then((result) => {
            if (result) {
                let topTab = [];
                for (let k in result) {
                    const {title, tabseq, orderby, showCount, selectedBigType, reportDateRangeValue1, reportDateRangeValue2, reportDateRangeValue3,
                        selectedReportStatus, selectedReportType, reportPersonsStr, selectedSubDepOption, reportSubDepStr,
                        selectedDepOption, reportDepStr} = result[k]
                    topTab.push({
                        color: '#ff3232',
                        groupid: tabseq + "",
                        showcount: showCount == "1" ? true : false,
                        title: title,
                        viewcondition: tabseq + 1,
                        selectedBigType,
                        orderby,
                        reportDateRangeValue1,
                        reportDateRangeValue2,
                        reportDateRangeValue3,
                        selectedReportStatus,
                        selectedReportType,
                        reportPersonsStr,
                        selectedSubDepOption,
                        reportSubDepStr,
                        selectedDepOption,
                        reportDepStr
                    })
                }

                // 设置默认数据
                // if (topTab.length == 0) {
                //     let defaultTableDatas = toJS(ReportElementSettingStore.defaultTableDatas)
                //     if (Array.isArray(defaultTableDatas)) {
                //         defaultTableDatas.forEach((d, i) => {
                //             topTab.push({
                //                 color: '#ff3232',
                //                 groupid: d.id + "",
                //                 showcount: d.showCount == 1 ? true : false,
                //                 title: d.title,
                //                 viewcondition: d.id + 1,
                //                 reportDateRangeValue2: d.reportDateRangeValue2,
                //                 orderby: d.orderby,
                //                 selectedBigType: d.selectedBigType,
                //                 selectedPerformanceStatus: d.selectedPerformanceStatus
                //             })
                //         })
                //     }
                // }

                this.setState({
                    topTab
                }, () => {
                    this.setTabInitDatas()
                })
            }
        });
    }

    setTabInitDatas = () => {
        this.state.topTab.forEach((d, i) => {
            window.setTimeout(() => {
                this.getListData({
                    key: d.viewcondition
                });
            }, 0)
        })
    }

    onScrollEnd = () => {
        const {currListFirstQueryTotal, currListDatas, selectedTabKey} = this.state
        this.state.currListPageNum = parseInt(this.state.currListPageNum) + 1 + "";
        if (currListFirstQueryTotal && currListFirstQueryTotal.length > 0 && parseInt(currListFirstQueryTotal) > currListDatas.length) {
            this.getListData({
                key: selectedTabKey
            });
        }
    }

    onTabChange = (key) => {
        this.setState({
            selectedTabKey: key,
            currListDatas: [],
            currListPageNum: "1",
            currListFirstQueryTotal: ""
        }, () => {
            this.getListData({
                key
            })
        })
    }

    getOrderby = (orderbytxt) => {
        let orderbyField = []
        let orderbyType = []
        if (orderbytxt) {
            orderbytxt.split(',').forEach((d, i) => {
                let orderNameTypeArr = d.split("-")

                if (orderNameTypeArr[0] == getLabel(508773, '报告人员')) {
                    orderbyField.push("lastname")
                } else if (orderNameTypeArr[0] == getLabel(508774, '报告状态')) {
                    orderbyField.push("s_status")
                }

                if (orderNameTypeArr[1] == getLabel(384984, "降序")) {
                    orderbyType.push("desc")
                } else if (orderNameTypeArr[1] == getLabel(384985, "升序")) {
                    orderbyType.push("asc")
                }
            })
        }

        // 默认都添加按year,type2,planid排序
        orderbyField.push("year")
        orderbyField.push("type2")
        orderbyField.push("planid")
        orderbyType.push("desc")
        orderbyType.push("desc")
        orderbyType.push("desc")

        return {
            field: orderbyField.join(","),
            type: orderbyType.join(",")
        }
    }

    getListData = (params) => {
        this.setState({
            loading: true
        })

        const {StringUtilsStore, ReportElementSettingStore} = this.props

        const {orderby, selectedBigType, reportDateRangeValue1, reportDateRangeValue2, reportDateRangeValue3, 
            reportPersonsStr, selectedReportStatus, selectedReportType,
            selectedSubDepOption, reportSubDepStr, selectedDepOption, reportDepStr} = this.state.topTab[params.key - 1]
        let orderbyParam = this.getOrderby(orderby)

        let interfaceName = selectedBigType == "1" || selectedBigType == "2" ? "portalResultList" : "portalAccessAudit"
        let requestParams = {
            // operation: "1",
            // persontype: selectedBigType,
            orderby: orderbyParam.field,
            orderbytype: orderbyParam.type,
            pageNum: this.state.currListPageNum,
            pagesize: this.state.pageSize,
            total: this.state.currListFirstQueryTotal
        }
        if (selectedBigType == "1") {         // 我的报告
            requestParams.isoneself = "1"
        }
        if (selectedBigType == "2") {         // 能查看的报告
            requestParams.isoneself = "0"
        }
        if (StringUtilsStore.isNotEmpty(reportDateRangeValue1)) {
            requestParams.year = reportDateRangeValue1
        }
        if (StringUtilsStore.isNotEmpty(reportDateRangeValue2)) {
            requestParams.type1 = reportDateRangeValue2.substring(2)
        }
        if (StringUtilsStore.isNotEmpty(reportDateRangeValue3)) {
            let type2Arr = []
            reportDateRangeValue3.split(",").forEach((d, i) => {
                type2Arr.push(d.substring(d.lastIndexOf("-") + 1))
            })
            requestParams.type2 = type2Arr.join(",")
        }
        if (StringUtilsStore.isNotEmpty(reportPersonsStr)) {
            let hrmidsArr = []
            reportPersonsStr.split(",").forEach((d, i) => {
                hrmidsArr.push(d.split("-")[0])
            })
            requestParams.hrmids = hrmidsArr.join(",")
        }
        if (StringUtilsStore.isNotEmpty(selectedReportStatus)) {
            requestParams.status = selectedReportStatus
        } else {
            // requestParams.status = ReportElementSettingStore.reportStatusOptions.map((d, i) => {
            //     return d.key
            // }).join(',')
        }
        if (StringUtilsStore.isNotEmpty(selectedSubDepOption)) {
            requestParams.includesub = selectedSubDepOption == "1" ? "3" : 
                                        selectedSubDepOption == "2" ? "1" :
                                        selectedSubDepOption == "3" ? "2" : ""
        }
        if (StringUtilsStore.isNotEmpty(reportSubDepStr)) {
            let subcompanyids = []
            reportSubDepStr.split(",").forEach((d, i) => {
                subcompanyids.push(d.split("-")[0])
            })
            requestParams.subcompanyids = subcompanyids.join(",")
        }
        if (StringUtilsStore.isNotEmpty(selectedDepOption)) {
            requestParams.includedept = selectedDepOption == "1" ? "3" : 
                                        selectedDepOption == "2" ? "1" :
                                        selectedDepOption == "3" ? "2" : ""
        }
        if (StringUtilsStore.isNotEmpty(reportDepStr)) {
            let departmentids = []
            reportDepStr.split(",").forEach((d, i) => {
                departmentids.push(d.split("-")[0])
            })
            requestParams.departmentids = departmentids.join(",")
        }

        WeaTools.callApi('/api/workrelate/plan/' + interfaceName, 'GET', requestParams).then((result) => {
            if (result) {
                let listDatas =  []
                let groupid = params.key - 1 + ""

                result.datas && result.datas.forEach((d, i) => {
                    if (selectedBigType == "3") {
                        d.comsbtn = [
                            {
                                com: getLabel(236, '退回'),
                                type: "return"
                            },
                            {
                                com: getLabel(142, '批准'),
                                type: "approve"
                            }
                        ]
                    } else {
                        d.comsbtn = []
                    }
                    listDatas.push(d)
                })

                this.state.counts[groupid] = result.iTotal
                this.setState({
                    counts: this.state.counts,
                    loading: false
                })

                if (params.key == this.state.selectedTabKey) {
                    listDatas.forEach((d, i) => {
                        this.state.currListDatas.push(d)
                    })
                    this.setState({
                        currListDatas: this.state.currListDatas,
                        currListFirstQueryTotal: result.iTotal + ""
                    })
                }
            }
        });
    }

    getMoreListData = (params) => {
        const {ReportElementViewStore, StringUtilsStore} = this.props
        //ReportElementViewStore.changeLoading(true)

        // const {orderby} = ReportElementViewStore.topTab[params.key - 1]
        // let orderbyParam = this.getOrderby(orderby)
        // WeaTools.callApi('/api/workrelate/task/getMoreList', 'GET', {
        //     orderby: orderbyParam.field,
        //     orderbytype: orderbyParam.type,
        //     pagenum: params.pagenum,
        //     pagesize: params.pagesize,
        //     sorttype: 1,
        //     total: this.state.currListFirstQueryTotal,
        //     excludeids: this.state.currListExcludedTaskIds.join(",")
        // }).then((result) => {
        //     //window.console.log(result)
        //     if (result) {
        //         result.datas.forEach((d, i) => {
        //             this.state.currListDatas.push(d)
        //         })
        //         this.setState({
        //             loading: false,
        //             currListDatas: this.state.currListDatas,
        //             currListHasMore: result.hasmore == "2" ? true : false
        //         })
        //     }
        // });
    }

    formatStatus = (statusHtml) => {
        if (statusHtml) {
            let idx = statusHtml.indexOf("</span>")
            if (idx != -1) {
                return statusHtml.substring(0, idx + 7)
            }
            return statusHtml
        }
        return ""
    }

    getReportStatusName = (status) => {
        const {ReportElementSettingStore} = this.props
        let statusName = ''
        ReportElementSettingStore.reportStatusOptions.forEach((d, i) => {
            if (d.key == status) {
                statusName = d.showname
            }
        })
        return statusName
    }

    onReportListRightBtnClick = (e) => {
        let elementid = e.target.id
        let innerText = e.target.innerText
        let operationType = e.target.getAttribute("type")
        let recordid = elementid.substring(elementid.lastIndexOf("-") + 1)
        let btnidx = elementid.substring(elementid.lastIndexOf("_") + 1, elementid.lastIndexOf("-"))
        let planid = this.state.currListDatas[parseInt(recordid) - 1].planid || ""
        Modal.confirm({
            title: getLabel(131329, '信息确认'),
            content: operationType == "approve" ? getLabel(508763, '确认批准？') : getLabel(508765, '确认退回？'),
            onOk: () => {
                WeaTools.callApi('/api/workrelate/plan/auditPlan', 'GET', {
                    planid,
                    // operation: innerText == "批准" ? "approve" : "return"
                    operation: operationType
                }).then((result) => {
                    if (result) {
                        if (result.api_status == '1') {
                            this.state.counts[parseInt(this.state.selectedTabKey) - 1 + ""] -= 1
                            this.state.currListDatas = this.state.currListDatas.filter((item, index) => {
                                return parseInt(recordid) - 1 != index
                            })

                            this.setState({
                                counts: this.state.counts,
                                currListDatas: this.state.currListDatas
                            })
                        } else {
                            message.warn(getLabel(508767, '无权限操作！'))
                        }
                    }
                })
            }
        })
    }

    render() {
        const { right } = this.state
        const {ReportElementViewStore, ReportElementSettingStore} = this.props

        return right == "1" ? (
            <div className="portal-report-element-view">
                <div>
                    <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@wqtjv2`}
                        datas={this.state.topTab}
                        counts={this.state.counts}
                        keyParam="viewcondition"
                        countParam="groupid"
                        onChange={this.onTabChange}
                        selectedKey={this.state.selectedTabKey}
                    />
                </div>
                <div>
                    <WeaNewScrollPagination ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScrollPagination@9up0xc`} height={125} loading = {this.state.loading} intervalTime={500} offset={10} onScrollEnd = {this.onScrollEnd}>
                        <div className="list-container">
                            {
                                this.state.currListDatas.map((d, i) => {
                                    return (
                                        <div className="report-wrapper" id={"report-" + (i + 1)}>
                                            <span className="report-title" title={d.planname} onClick={(e) => {
                                                d.planid ? 
                                                window.open("/spa/workrelate/static/index.html#/main/workrelate/plan/planView?planid=" + d.planid) :
                                                window.open("/spa/workrelate/static/index.html#/main/workrelate/plan/planView?resourceid=" + (d.resourceid || "") + "&year=" + (d.year || "") + "&type1=" + (d.type1 || "") + "&type2=" + (d.type2 || ""))        
                                            }}>
                                                {d.planname}
                                            </span>
                                            <span className="report-relate" title={d.lastname}>{d.lastname}</span>
                                            {/* <span className="report-status" dangerouslySetInnerHTML={{ __html: this.formatStatus(d.status)}}></span> */}
                                            {/* <span className="report-status">
                                                {this.getStatusNameByKey(d.status)}
                                            </span> */}
                                            {/* <span className="report-status" title={this.getReportStatusName(d.status)}>{this.getReportStatusName(d.status)}</span> */}
                                            <span className="report-status" title={d.statusname}>{d.statusname}</span>
                                            <span className="report-operation-wrapper">
                                                {
                                                    d.comsbtn.map((dd, ii) => {
                                                        return (
                                                            <span id={`report-operation_${ii}-${i + 1}`} type={dd.type} className="report-operation" onClick={this.onReportListRightBtnClick}>{dd.com}</span>
                                                        )
                                                    })
                                                }
                                            </span>
                                        </div>
                                    )
                                })
                            }
                            {
                                ((!this.state.currListDatas || this.state.currListDatas.length == 0) && !this.state.loading) ? ReportElementViewStore.nodata : ""
                            }
                        </div>
                        <div className="loadingexample">
                            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@15hgir`} spinning={this.state.loading}></Spin>
                        </div>
                    </WeaNewScrollPagination>
                </div>
            </div>
        ) : (right == "0" ? ReportElementViewStore.noright : "")
    }
}

export default View;
